package fm.cheyiwang.controller;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import fm.controller.BaseController;
import fm.dto.NeiyiUser;
import fm.entity.WxUser;
import fm.entityEnum.CarouselType;
import fm.exception.BizException;
import fm.exception.TokenInvalidException;
import fm.mongoService.UserService;
import fm.web.CurrentRequest;
import fm.web.MediaTypes;
import fm.yichenet.mongo.service.GoodMgrService;
import fm.yichenet.mongo.service.MerchantService;
import fm.yichenet.mongo.service.ShopMgrService;
import fm.yichenet.mongo.service.VisitHistoryService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by 宏炜 on 2017-06-13.
 */
@Controller
@RequestMapping("appshop")
public class AppShopController extends BaseController {

    @Autowired
    MerchantService merchantService;

    @Autowired
    GoodMgrService goodMgrService;

    @Autowired
    ShopMgrService shopMgrService;
    @Autowired
    UserService userService;
    @Autowired
    VisitHistoryService visitHistoryService;


    @ResponseBody
    @RequestMapping(value = "index", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map index(@RequestParam(value = "shopId", required = true) String shopId) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            NeiyiUser user = userService.getById(shopId);

            if (user == null) {
                throw new BizException("未找到商户信息!");
            }

            if (user.getUserType() != 2 && user.getUserType() != 3 && user.getUserType() != 4) {
                throw new BizException("没有找到对应的店铺信息！");
            }

            NeiyiUser shopInfo = user;
            Map<String, Object> query = new HashedMap();
            query.put("shop_id", shopId);
            DBObject sort = new BasicDBObject("priority", Sort.Direction.DESC.toString());
            List<DBObject> goods = goodMgrService.getShopGoodList(query, sort);

            try {
                //更新浏览记录 并且更新首次登陆的店铺ID
                WxUser currentUser = (WxUser) CurrentRequest.getCurrentUser();
                if (currentUser != null) {
                    DBObject log = new BasicDBObject();
                    log.put("shop_id", shopId);
                    if (StringUtils.isNotEmpty(user.getUserAdd().getProvince())) {
                        log.put("province", user.getUserAdd().getProvince());
                    }
                    if (StringUtils.isNotEmpty(user.getUserAdd().getCity())) {
                        log.put("city", user.getUserAdd().getCity());
                    }
                    log.put("visit_time", new Date());
                    log.put("user_id", currentUser.getId());
                    visitHistoryService.addVisitLog(log);
                }

            } catch (TokenInvalidException ex) {
                LOGGER.error("登陆已经过期了拉");
            } catch (Exception ex) {
                LOGGER.error("获取用户登陆信息失败:", ex);
            }

            shopInfo.setGoods(goods);
            res.put("data", shopInfo);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("访问店铺首页发生错误", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("访问店铺首页发生错误", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决!");
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "shopList", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map shopList(String shopType, String province, String city,
                        @RequestParam(value = "keyword", required = false, defaultValue = "") String keyword,
                        @RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize,
                        @RequestParam(value = "pageNum", required = true, defaultValue = "1") Integer pageNum,
                        @RequestParam(value = "latitude", required = false, defaultValue = "0") Double latitude,
                        @RequestParam(value = "longitude", required = false, defaultValue = "0") Double longitude) throws Exception {
        Map<String, Object> res = new HashedMap();
        List shopList = shopMgrService.getShopList(shopType, keyword, longitude, latitude, province, city, pageSize, pageNum);

        res.put("data", shopList);
        this.success(res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "collectShop", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map collectShop(@RequestParam(value = "shopId", required = true) String shopId) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            NeiyiUser user = (NeiyiUser) getCurrentUser();
            shopMgrService.collectShop(shopId, user);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "unCollectShop", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map unCollectShop(@RequestParam(value = "shopId", required = true) String shopId) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            NeiyiUser user = (NeiyiUser) getCurrentUser();
            shopMgrService.unCollectShop(shopId, user);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "collectionShopList", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map collectionShopList(@RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize,
                                  @RequestParam(value = "pageNum", required = true, defaultValue = "1") Integer pageNum) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            NeiyiUser user = (NeiyiUser) getCurrentUser();
            List shopList = shopMgrService.getCollectionShopList(user, pageSize, pageNum);
            res.put("data", shopList);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "checkCollectShop", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map checkCollectShop(@RequestParam(value = "shopId", required = true) String shopId) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            NeiyiUser user = (NeiyiUser) getCurrentUser();
            res = shopMgrService.checkCollectShop(shopId, user);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "userList", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map userList(@RequestParam(value = "userType", required = false) Integer userType,
                        @RequestParam(value = "keyword", required = false) String keyword) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            List<NeiyiUser> shopList = userService.getUserList(userType, keyword);
            res.put("data", shopList);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "userPageList", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map userPageList(@RequestParam(value = "userType", required = false) Integer userType,
                            @RequestParam(value = "keyword", required = false) String keyword,
                            @RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize,
                            @RequestParam(value = "pageNum", required = true, defaultValue = "1") Integer pageNum) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            List<NeiyiUser> shopList = userService.getUserPageList(userType, keyword, pageSize, pageNum);
            res.put("data", shopList);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "addUserByPhone", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map addUserByPhone(@RequestParam(value = "phone", required = true) String phone) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            NeiyiUser user = new NeiyiUser();
            if (phone != null) {
                user.setPhone(phone);
                user.setUserType(1);
                userService.addUser(user);
            }
            res.put("data", user);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "getUserByPhone", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map getUserByPhone(@RequestParam(value = "phone", required = true) String phone) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            NeiyiUser phoneUser = userService.getUserByPhone(phone);
            res.put("data", phoneUser);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "carousel/list", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map carouselList(@RequestParam(value = "type", required = false) CarouselType type,
                            @RequestParam(value = "shopId", required = true) String shopId) throws Exception {
        Map<String, Object> res = new HashedMap();
        try {
            List<DBObject> shopCarouselList = userService.getCarouselListByUserId(type, shopId);
            res.put("data", shopCarouselList);
            this.success(res);
        } catch (BizException ex) {
            this.failed(res, ex);
        }
        return res;
    }

}
